package com.example.kotlinpractice.compare

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlinpractice.R


/**
 *
 * Created by dingshuhong on 2020/10/27.
 */
class CompareRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {

    private var firstVisibleItemPosition = 0
    private var lastVisibleItemPosition = 0
    private var offset = 0

    init {
        addOnScrollListener(object : OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    /**
     * 获得屏幕内的Position
     */
    private fun findEyeablePosition() {
        val layoutManager = layoutManager
        if (layoutManager is LinearLayoutManager) {
            firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
            lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
        }
    }

    /**
     * 当某个item滚动的时候，屏幕内的其他item跟着滚动
     * @param moveX
     */
    fun scrollTo(moveX: Int) {
        this.offset = moveX
        findEyeablePosition()
        for (i in firstVisibleItemPosition..lastVisibleItemPosition) {
            startScrollRowView(getRowRecyclerView(i), moveX)
        }
        /*startAnmateView(
            findAnimateScrollView(mCurrentHeader),
            offset
        )*/ //mCurrentHeader scrollView move
        invalidate()
    }

    private fun startScrollRowView(rowRecyclerView: RowRecyclerView, moveX: Int) {
       // scrollView.smoothScrollTo(moveX, 0)
    }

    private fun getRowRecyclerView(position: Int): RowRecyclerView {
        var itemView = findViewHolderForAdapterPosition(position)?.itemView
        return itemView?.findViewById(R.id.row_recycler_view) as RowRecyclerView
    }


}